'use strict';

const path = require('path');
const Controller = require('egg').Controller;

class UploadController extends Controller {
  async upload() {
    const ctx = this.ctx;
    // const { file } = ctx.service;
    try {
      const parts = ctx.multipart();
      const params = {};
      let object;
      let part;
      while ((part = await parts())) {
        if (part.length) {
          // arrays are busboy fields
          // field: part[0]; value: part[1]; valueTruncated: part[2]; fieldnameTruncated: part[3];
          const field = part[0];
          const value = part[1];
          params[field] = value;
        } else {
          // otherwise, it's a stream
          // field: part.fieldname; filename: part.filename; encoding: part.encoding; mime: part.mime;
          // file handle
          const file = path.parse(part.filename);
          object = await ctx.oss.put(
            `egg-example-${file.name}-${Date.now()}${file.ext}`,
            part
          );
        }
      }
      if (object) {
        ctx.success({ data: { url: object.url } });
        // todo: 保存文件上传记录， 上传时间，上传人
      } else {
        ctx.error({ detail: 'please select a file to upload！' });
      }
    } catch (error) {
      console.log(error);
      ctx.error({ detail: error });
    }
  }

  async destroy() {
    const ctx = this.ctx;
    const { file } = ctx.service;
    const data = await file.destroy(ctx.params);
    ctx.success({ data });
  }
}

module.exports = UploadController;
